package com.yupi.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yupi.usercenter.commons.BaseResponse;
import com.yupi.usercenter.commons.ErrorCode;
import com.yupi.usercenter.commons.ResponseUtils;
import com.yupi.usercenter.exception.BusinessException;
import com.yupi.usercenter.pojo.Users;
import com.yupi.usercenter.pojo.request.UserLoginRequest;
import com.yupi.usercenter.pojo.request.UserRegisterRequest;
import com.yupi.usercenter.service.UsersService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

import static com.yupi.usercenter.constant.UserConstant.MANAGER;
import static com.yupi.usercenter.constant.UserConstant.USER_LOGIN_STATE;


/**
 * @author 麦翔盛
 * @description: 用户中心控制类
 * @date 2022/4/4 23:30
 */
@RestController()
@RequestMapping("/user")
@CrossOrigin
public class  UserController {
    @Resource
    private UsersService usersService;

    /**
     * 用户注册
     *
     * @param userRegisterRequest 用户注册请求
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        //获取用户数据
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();
        //判空
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planetCode)) {
            throw new BusinessException(ErrorCode.NULL_ERROR,"请求参数为空");
        }
        //获取是否注册成功,返回新增用户id
        long userId = usersService.userRegister(userAccount, userPassword, checkPassword, planetCode);
        return ResponseUtils.success(userId);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest 用户注册请求
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<Users> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        //获取用户数据
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        //判空
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR,"请求参数为空");
        }

        //获取是否注册成功

        Users user = usersService.userLogin(userAccount, userPassword, request);
        request.getSession().setAttribute(USER_LOGIN_STATE, user);
        request.getSession().setAttribute("user", 123);
        return ResponseUtils.success(user);
    }

    /**
     * 用户注销
     * @param request 请求
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (null == request){
            throw new BusinessException(ErrorCode.NULL_ERROR,"请求参数为空");
        }
        int result = usersService.userLogout(request);
        return ResponseUtils.success(result);
    }

    /**
     * 查询用户
     *
     * @param username 用户名
     */
    @GetMapping("/search")
    public BaseResponse<List<Users>> searchUsers(String username, HttpServletRequest request) {
        //判断是否是管理员
        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH,"不是管理员");
        }
        //根据条件查询
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        //判空
        if (!StringUtils.isAnyBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<Users> userList = usersService.list(queryWrapper);
        List<Users> usersList = userList.stream().map(users -> usersService.getSafetyUser(users)).collect(Collectors.toList());
        return ResponseUtils.success(userList);

    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(long id, HttpServletRequest request) {
        //判断是否是管理员
        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCode.NULL_ERROR,"请求参数为空");
        }
        //判断账号是否超出了边界
        if (id < 1) {
            throw new BusinessException(ErrorCode.ILLEGAL_USER_ERROR,"账户id小于1非法用户");
        }
        //返回删除结果
        boolean result = usersService.removeById(id);
        return ResponseUtils.success(result);
    }

    /**
     * 判断是否为管理员
     *
     * @param request 请求信息
     * @return 返回是否为管理员
     */
    private boolean isAdmin(HttpServletRequest request) {
        //判断是否是管理员
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        Users users = (Users) userObj;
        if (null == users || !MANAGER.equals(users.getRole())) {
            return false;
        }
        return true;
    }

    /**
     * 获取当前用户 存在session中的用户
     * @param request
     * @return
     */
    @GetMapping("/current")
    public BaseResponse<Users> getCurrentUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        System.out.println(request.getSession().getAttribute("user"));
        Users currentUser = (Users) userObj;

        //判空
        if (null == currentUser) {
            throw new BusinessException(ErrorCode.NO_LOGIN);
        }
        //TODO : 校验用户是否合法 比如该用户的用户状态是否合法
        //从数据中获取该用户的数据,再次从数据库中取出是防止除了id之外的数据发生改变
        Users user = usersService.getById(currentUser.getId());
//        Users user = usersService.getById(5);
        //返回脱敏用户
        return ResponseUtils.success(user);

    }
}
